import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'
import traceDetail from '../apis/traceDetail'

function parseTrace(data){
  return _.extend({},data,{
    startTime:data['timestamp'],
    endTime:data['timestamp']+data['executeTime'],
    webViewDetail:JSON.parse(data['webViewDetail']),
    baseDetail:JSON.parse(data['baseDetail'])
  });
}

export default class TraceScope extends Scope {
  constructor(props){
    super();
    this.traceId = props.routeParams.traceId
    this.$state = {
      trace:null,
      resource:null
    }
    this.traceApi = traceDetail({
      id:this.traceId,
      urlName:'webViewdetail'
    })
    this.resourceApi = traceDetail({
      urlName:'webview/'+this.traceId+'/resource'
    })
  }
  fetch(){
    this.traceApi.fetch().then((data,params) => {
      this.$state.trace = parseTrace(data)
      this.emit()
    })
    this.resourceApi.fetch().then((data,params) => {
      this.$state.resource = {
        resources:data.resources,
        initiatorTypeGroup:_(data.resources).groupBy('initiatorType'),
        hostGroup:_(data.resources).groupBy('host')
      }
      this.emit()
    })
  }
  $unload(){
  }
  $load(){
    var _this = this
    this.fetch();
  }
}
